package com.gavin.lingxi;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.gavin.lingxi.common.utils.DeviceUtils;
import com.gavin.lingxi.rtc.call.LiveActivity;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.QRCodeBean;
import com.google.zxing.common.BitMatrix;
import com.puppy.bingo.tools.GsonUtil;
import com.puppy.bingo.tools.StringUtils;
import com.puppy.bingo.tools.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.EnumMap;
import java.util.Map;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

import static com.google.zxing.client.android.Scanner.RETURN_SCAN_RESULT;
import static com.google.zxing.client.android.Scanner.SCAN_RESULT;

/**
 * Created by xiangfeng on 17/11/11.
 */

public class HomepageFragment extends Fragment implements
        View.OnClickListener {

    private static final String TAG = HomepageFragment.class.getSimpleName();
    private TextView title;
    private ImageView mScanImg;
    private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;
    private CompositeDisposable mDisposables = new CompositeDisposable();

    private RxPermissions mRxPermissions;
    private ImageView mIvQrCode;

    public static HomepageFragment newInstance() {
        HomepageFragment fragment = new HomepageFragment();
        return fragment;
    }


    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.iv_scan) {
            toScan();
        }
    }

    private void toScan() {

        Disposable disposable = mRxPermissions.requestEach(Manifest.permission.CAMERA)
                .all(permission -> {
                    if (permission.granted) {
                        return true;
                    } else {
                        if (Manifest.permission.CAMERA.equals(permission.name)) {
                            ToastUtils.show(getActivity(), R.string.open_camera_permission);
                        }
                    }
                    return false;
                }).subscribe(allGranted -> {
            if (allGranted) {
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, RETURN_SCAN_RESULT);
            }
        });
        mDisposables.add(disposable);
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        mRxPermissions = new RxPermissions(getActivity());
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
            container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        initUI(view);
        return view;
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RETURN_SCAN_RESULT) {
            if (resultCode != Activity.RESULT_OK || data == null) {
                return;
            }
            QRCodeBean<String> qrCodeBean = null;
            String result = data.getStringExtra(SCAN_RESULT);
            if(StringUtils.isEmpty(result)){
               return;
            }
            try {
                qrCodeBean = GsonUtil.GsonToBean(data.getStringExtra(SCAN_RESULT), QRCodeBean.class);

                if (qrCodeBean.getType() == 0) {
                    String robotId = qrCodeBean.getData();
                    initData(robotId);
                    videoChatClick();
                } else {
                    toMoreResult(result);
                }

            } catch (Exception e) {
                e.printStackTrace();
                toMoreResult(result);
            }
        }
    }


    private void toMoreResult(String data) {
        Intent intent = new Intent(getActivity(), MoreResultActivity.class);
        intent.putExtra(SCAN_RESULT,data);
        startActivity(intent);
    }



    private void initUI(View view) {
        title = view.findViewById(R.id.home_title);
        title.setText("灵犀通话");
        mScanImg = view.findViewById(R.id.iv_scan);
        mScanImg.setOnClickListener(this);
        mIvQrCode = view.findViewById(R.id.iv_qrcode);
        String uid = "" + (System.currentTimeMillis() / 1000);
        WertcSdk.getInstance().setUserId(uid);
        mIvQrCode.setImageBitmap(makeQRCodeBitmap(uid));
    }

    public void initData(String callUid) {

        if (!DeviceUtils.isNetworkAvailable(getActivity())) {
            ToastUtils.show(getActivity(), getResources().getString(R.string.common_network_err), Toast.LENGTH_SHORT);
            return;
        }

        WertcSdk.getInstance().setCallUid(callUid);
        WertcSdk.getInstance().reconnect();
    }


    public void videoChatClick() {   //视频模式

        Disposable disposable = mRxPermissions.requestEach(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
                .all(permission -> {
                    if (permission.granted) {
                        return true;
                    } else {
                        if (Manifest.permission.CAMERA.equals(permission.name)) {
                            ToastUtils.show(HomepageFragment.this.getContext(), R.string.open_camera_permission);
                        } else if (Manifest.permission.RECORD_AUDIO.equals(permission.name)) {
                            ToastUtils.show(HomepageFragment.this.getContext(), R.string.open_audio_permission);
                        }
                    }
                    return false;
                }).subscribe(allGranted -> {
            if (allGranted) {

                Intent intent = new Intent(getActivity(), LiveActivity.class);
                intent.putExtra(RTCParam.INTENT_CALL_TYPE, RTCParam.TYPE_CALLER);
                intent.putExtra(RTCParam.INTENT_USER_ID, WertcSdk.getInstance().getUserId());
                startActivity(intent);
            }
        });
        mDisposables.add(disposable);
    }

    private static String getEncoding(CharSequence contents) {
        for (int i = 0; i < contents.length(); i++) {
            if (contents.charAt(i) > 0xFF) {
                return "UTF-8";
            }
        }
        return null;
    }

    private Bitmap makeQRCodeBitmap(String id) {
        if (TextUtils.isEmpty(id)) {
            return null;
        }

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", 0);
            jsonObject.put("data", id);
            jsonObject.put("msg", "");
            String str = jsonObject.toString();
            Map<EncodeHintType, Object> hints = null;
            //获取字符编码
            String encoding = getEncoding(str);
            if (encoding != null) {
                hints = new EnumMap<>(EncodeHintType.class);
                hints.put(EncodeHintType.CHARACTER_SET, encoding);
            }


            //通过字符串创建二维矩阵
            BitMatrix result=new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE,450,450,hints);
            int width = result.getWidth();
            int height = result.getHeight();
            int[] pixels = new int[width * height];

            for (int y = 0; y < height; y++) {
                int offset = y * width;
                for (int x = 0; x < width; x++) {
                    //根据二维矩阵数据创建数组
                    pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
                }
            }
            //创建位图
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            //将数组加载到位图中
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }  catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


}